<template>
  <div id="Content">
    <div style="height: 2px">
      <span>
        <hr color="black">
        <hr color="black">
      </span>
    </div>

    <div class="imui-center">
      <lemon-imui
        :user="user"
        ref="IMUI"
        width="100%"
        :contextmenu="contextmenu"
        :contact-contextmenu="contactContextmenu"
        :theme="theme"
        :hide-menu="hideMenu"
        :hide-menu-avatar="hideMenuAvatar"
        :hide-message-name="hideMessageName"
        :hide-message-time="hideMessageTime"
        @change-menu="handleChangeMenu"
        @change-contact="handleChangeContact"
        @pull-messages="handlePullMessages"
        @message-click="handleMessageClick"
        @menu-avatar-click="handleMenuAvatarClick"
        @send="handleSend"
      >
        <template #cover>
          <div class="cover">
            <i class="lemon-icon-message"></i>
            <p><b>Community Loadind...</b></p>
          </div>
        </template>
      </lemon-imui>
    </div>

    <el-dialog
      title="添加好友或群组"
      :visible.sync="dialogVisible"
      width="50%"
    >
      
      <el-tabs type="border-card">
        <el-tab-pane label="找人">
          <span>
            <el-input v-model="userKeyword" placeholder="请输入用户名" class="keyword"></el-input>
            <el-button @click="findUsers" type="primary" icon="el-icon-search">搜索</el-button>

            

            <el-table
              :data="userResults"
              style="width: 100%">
              <el-table-column
                label="头像"
                width="180">
                <el-avatar size="large" :src="circleUrl"></el-avatar>
              </el-table-column>
              <el-table-column
                label="用户名"
                width="180">
                <template slot-scope="scope">
                  <div slot="reference" class="name-wrapper">
                    <el-tag size="medium">{{ scope.row.id }}</el-tag>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    @click="addFriend(scope.row.id)">添加</el-button>
                </template>
              </el-table-column>
            </el-table>

          </span>
        </el-tab-pane>
        <el-tab-pane label="找群">
          <span>
            <el-input v-model="groupKeyword" placeholder="请输入群号" class="keyword"></el-input>
            <el-button @click="findGroups" type="primary" icon="el-icon-search">搜索</el-button>

            <el-table
              :data="groupResults"
              style="width: 100%">
              <el-table-column
                label="头像"
                width="180">
                <el-avatar size="large" :src="circleUrl"></el-avatar>
              </el-table-column>
              <el-table-column
                label="群号"
                width="180">
                <template slot-scope="scope">
                  <div slot="reference" class="name-wrapper">
                    <el-tag size="medium">{{ scope.row.id }}</el-tag>
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                label="群名称"
                width="180">
                <template slot-scope="scope">
                  <div slot="reference" class="name-wrapper">
                    <el-tag size="medium">{{ scope.row.displayName }}</el-tag>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    @click="enterGroup(scope.row.id)">添加</el-button>
                </template>
              </el-table-column>
            </el-table>

          </span>
        </el-tab-pane>
        <el-tab-pane label="建群">
          <span>
            <el-form ref="form" :model="group" label-width="80px">
              <el-form-item label="群号：">
                <el-input v-model="group.id"></el-input>
              </el-form-item>
              <el-form-item label="群名：">
                <el-input v-model="group.name"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="createGroup(group.id, group.name)">立即创建</el-button>
              </el-form-item>
            </el-form>
          </span>
        </el-tab-pane>
      </el-tabs>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Vue from 'vue';
import { mapState } from 'vuex';
import LemonMessageVoice from "./lemon-message-voice";
import EmojiData from "./emoji.js";
import { reqFindUsers, reqFindGroups, reqAddFriend, reqEnterGroup, reqCreateGroup, reqFriendsAndGroups ,
          getHistoryMessages, addHistoryMessage} from "@/api"
Vue.component(LemonMessageVoice.name, LemonMessageVoice);

const getTime = () => {
  return new Date().getTime();
};
const generateRandId = () => {
  return Math.random()
    .toString(36)
    .substr(-8);
};

const generateMessage = (message) => {
  return {
    id: message.id, //消息的id
    status: message.status,  //消息的状态
    type: message.type, //消息的类型
    sendTime: message.sendTime,  //消息的发送时间
    content: message.content,  //生成随机的消息内容
    toContactId: message.toContactId,  //消息是发送给谁的
    fromUser: message.fromUser, //消息的来源是谁
  };
};

export default {
  name: "ChatMain",
  data() {
    return {
      //当前用户的信息
      user: {},

      //messages
      messages: [],
      historyMessage:[],      //用于储存每次会话的历史消息

      //是否显示添加好友或群组的对话框
      dialogVisible: false,
      //添加好友界面当前选中的index
      activeIndex: '1',
      //搜索关键词
      userKeyword: '',
      groupKeyword: '',
      //搜索结果
      userResults: [],
      groupResults: [],
      //是一个死的头像地址
      circleUrl: "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png",
      //创建群的信息
      group: {
        id: '',
        name: '',
      },


      //联系人列表
      contactList: [],

      //以下的属性没有用，但不要改
      theme: "default", //主题
      contextmenu: [],  //在聊天框右击鼠标的菜单选项
      hideMenuAvatar: false,  //是否隐藏菜单的图像
      hideMenu: false,        //是否隐藏菜单
      hideMessageName: false, //是否隐藏消息名
      hideMessageTime: false,  //是否隐藏消息时间

      //在群和好友界面鼠标右击时的选项菜单
      contactContextmenu: [
        {
          text: "删除该聊天",
          click: (e, instance, hide) => {
            const { IMUI, contact } = instance;
            IMUI.updateContact({
              id: contact.id,
              lastContent: null,
            });
            if (IMUI.currentContactId == contact.id) IMUI.changeContact(null);
            hide();
          },
        },
        {
          text: "设置备注和标签",
        },
        {
          click(e, instance, hide) {
            const { IMUI, contact } = instance;
            IMUI.removeContact(contact.id);
            if (IMUI.currentContactId == contact.id) IMUI.changeContact(null);
            hide();
          },
          color: "red",
          text: "删除好友",
        },
      ],
    };
  },
  computed:{
    ...mapState({
      //注入state参数
      loginAccount: state=>state.account.loginAccount,
    })
  },
  //挂载函数
  async mounted() {
    //首先初始化用户信息
    this.user.id = this.loginAccount.username;
    this.user.displayName = this.loginAccount.username;
    this.user.avatar = '';

    this.creatSocket();
    this.eventMsg();
    this.init();        //初始化界面，加载历史消息

    //获取所有联系人，并存储到contactList中
    let res = await reqFriendsAndGroups();
    if(res.data){
      this.contactList = res.data;
      for(let contact of this.contactList){
        contact.lastContent = decodeURI(contact.lastContent);
      }
    }
    
    // console.log('在此之前');
    // console.log(this.contactList);

    const { IMUI } = this.$refs;
    //初始化导航栏（历史消息，联系人，添加好友与群组）
    IMUI.initMenus([
      {
        name: "messages",
      },
      {
        name: "contacts",
      },
      {
        name: "custom2",
        title: "添加好友与群组",
        unread: 0,
        click: () => {
          //在显示之前，将之前的搜索关键词和结果清空
          this.userKeyword = '';
          this.groupKeyword = '';
          this.userResults = [];
          this.groupResults = [];
          this.group.id = '';
          this.group.name = '';
          this.dialogVisible = true;
        },
        render: (menu) => {
          return <i class="lemon-icon-group" />;
        },
        isBottom: true,
      },
    ]);
    //初始化联系人
    IMUI.initContacts(this.contactList);
    //初始化表情，文件上传，图片
    IMUI.initEditorTools([
      {
        name: "emoji",
      },
      {
        name: "uploadFile",
      },
      {
        name: "uploadImage",
      },
    ]);
    IMUI.initEmoji(EmojiData);
  },
  //在离开当前界面之前
  beforeDestroy(){
    this.closeWebSocket();
  },
  methods: {
    //初始化聊天界面，加载历史聊天信息
    async init(){
      let res = await getHistoryMessages();
      let that = this;
      let {IMUI} = that.$refs; 
      let hisMsg = res.data;
      console.log("获取历史消息：");
      console.log(hisMsg);
      // let hisMsg=JSON.parse(JSON.stringify(res.data));      //在使用使用深拷贝，否则会报错
      if(hisMsg != null){
        for(let message of hisMsg){
          message.content = decodeURI(message.content);  //将内容解码
          that.messages.push(message);
        }
      };
      // console.log("历史消息加载完毕结束");
      
    },


//离开界面，关闭WebSocket连接
    closeWebSocket(){
      let that=this;
      this.$global.ws.close();
      this.$global.ws.onclose = function(){
        let hisMsg = JSON.parse(sessionStorage.getItem("historyMessages"));     //获取储存的历史消息
        if(hisMsg != null){
          let newHis = hisMsg.concat(that.historyMessage);            //更新
          sessionStorage.setItem("historyMessages",JSON.stringify(newHis));           //将历史消息储存
        }
        else
          sessionStorage.setItem("historyMessages",JSON.stringify(that.historyMessage));
        console.log("连接已断开");
      };
    },

    //实例化websocket
    creatSocket() {
      let that = this;
      if ("WebSocket" in window) {
        //实例化websocket	 
        that.ws = new WebSocket("ws://localhost:8088/api/chat");
        //保存设置全局websocket对象
        that.$global.setWs(that.ws);
        //监听websocket连接打开方法
        that.ws.onopen = function() {
          console.log("打开websocket")
          // that.init();                //初始化用户历史消息
        }
        //监听websocket错误方法
        that.ws.onerror = function(ev) {
          console.log("连接已出错...");
            //延迟执行重连
            setTimeout(() => {
              that.creatSocket();
            }, that.$global.delay);
        };
        //监听websocket关闭方法
        that.ws.onclose = function(ev) {
          // 关闭 websocket
          console.log("连接已关闭...");
          //延迟执行重连
          setTimeout(() => {
            that.creatSocket();
          }, that.$global.delay);
        };
        //监听websocket接收消息事件（接收来自服务器的实时消息）
        that.ws.onmessage = function(res) {
          console.log("App.vue收到服务器内容", res.data);
        };
      } else {
        // 浏览器不支持 WebSocket
        console.log("您的浏览器不支持 WebSocket!");
      }
    },

    //当接收到消息时的处理
    eventMsg(){
      let that = this;
      this.$global.ws.onmessage = (res) => {
        let message = JSON.parse(res.data);
        console.log(message);
        console.log(message.content);
        this.contactList = [];
        const { IMUI } = this.$refs;
        //这证明是一条广播消息
        if(message.toContactId == null && message.fromUser == null){
          //此时有人下线
          if(message.type=="offLine"){
            IMUI.removeContact(message.content.id);
          }
          else{      //此时有人上线
            for(let contactData of message.content){
            //联系人列表进行添加
            contactData.lastContent=decodeURI(contactData.lastContent);
            IMUI.appendContact(contactData);
          }
          }
        }
        //其他统统按照普通消息处理
        else{
          console.log('我收到了消息');
          console.log(message);

          this.messages.push(message);
          console.log(message);
          IMUI.appendMessage(message, true);
          console.log(IMUI.getMessages());
          console.log(this.messages);
          that.historyMessage.push(message);          
        };
      }
    },

    scrollToTop() {
      document.body.scrollIntoView();
    },
    //当左上角的头像被点击时该函数执行（可以后续拓展）
    handleMenuAvatarClick() {
      console.log('左上角的头像被点击了');
    },
    //用来重发消息（基本没什么用）
    handleMessageClick(e, key, message, instance) {
      console.log("点击了消息", e, key, message);

      if (key == "status") {
        instance.updateMessage({
          id: message.id,
          status: "going",
          content: "正在重新发送消息...",
        });
        setTimeout(() => {
          instance.updateMessage({
            id: message.id,
            status: "succeed",
            content: "发送成功",
          });
        }, 2000);
      }
    },

    //追加一条消息
    appendMessage(msg) {
      const { IMUI } = this.$refs;
      const message = generateMessage(msg);
      message.fromUser = {
        ...message.fromUser,
        ...this.user,
      };
      IMUI.appendMessage(message, true);
    },

    //更换查看的聊天记录框
    handleChangeContact(contact, instance) {
      instance.updateContact({
        id: contact.id,
        unread: 0,
      });
      instance.closeDrawer();
    },

    //进行发送消息(即send按钮的回调事件)，后期可以与websocket结合
    handleSend(message, next, file) {
      // console.log('发送按钮被点击了');
      // console.log(message);
      message.status = 'succeed';          
      this.historyMessage.push(message);           //---------------------
      this.ws.send(JSON.stringify(message));
      this.addHisMsg(message);
    },

    //此函数用于获取历史消息（第一次打开与联系人聊天的界面会调用此函数）
    handlePullMessages(contact, next) {
      console.log("我在获取历史消息...");
      const { IMUI } = this.$refs;
      const historyMessages = [];
      if(contact.index=="群组"){
        for(let msg of this.messages){
          if(msg.toContactId==contact.id){
            historyMessages.push(msg);
          }
        }
      }
      else{
        for(let msg of this.messages){
          if(contact.id == msg.fromUser.id && msg.toContactId == this.user.id || msg.fromUser.id == this.user.id && msg.toContactId == contact.id){
            historyMessages.push(msg);
          }
        }
      }
      next(historyMessages, true);
    },

    //更换菜单
    handleChangeMenu() {
      console.log("Event:change-menu");
    },

    //在对话框进行选择
    handleSelect(key, keyPath) {
      this.activeIndex = keyPath[0];
    },

    //创建群
    onSubmit() {
      console.log('submit!');
    },

    //搜索用户
    async findUsers(){
      let res = await reqFindUsers(this.userKeyword);
      this.userResults = res.data;
    },

    //搜索群组
    async findGroups(){
      let res = await reqFindGroups(this.groupKeyword);
      this.groupResults = res.data;
    },

    //创建群组
    async createGroup(){
      let res = await reqCreateGroup(this.group.id, this.group.name);
      console.log(res);
      //这证明群号已经被占用
      if(res.status == 1){
        this.$message.error('群号已被占用，试试换个群号！');
      }
      else if(res.status == 0){
        const { IMUI } = this.$refs;
        res.data.lastContent=decodeURI(res.data.lastContent);
        IMUI.appendContact(res.data);
        this.$message({
          message: '群组已创建成功！',
          type: 'success'
        });
        this.dialogVisible = false;
        this.group.id = '';
        this.group.name = '';
      }
    },

    //添加好友
    async addFriend(friendId){
      let res = await reqAddFriend(friendId);
      console.log(res);
      //用户已经添加过该好友
      if(res.status == 100){
        this.$message.error('您已添加过该用户！');
      }else if(res.status == 0){
        const { IMUI } = this.$refs;
        res.data.lastContent=decodeURI(res.data.lastContent);
        IMUI.appendContact(res.data);
        this.$message({
          message: '添加好友成功！',
          type: 'success'
        });
      }
    },

    //添加群组
    async enterGroup(groupId){
      let res = await reqEnterGroup(groupId);
      console.log(res);
      //用户已经添加过该群组
      if(res.status == 100){
        this.$message.error('您已在该群组中！');
      }else if(res.status == 0){
        const { IMUI } = this.$refs;
        res.data.lastContent=decodeURI(res.data.lastContent);
        IMUI.appendContact(res.data);
        this.$message({
          message: '添加群组成功！',
          type: 'success'
        });
      }
    },

    async addHisMsg(message){
      // console.log("开始储存历史消息");
      //将时间戳的格式进行转化：
      let date = new Date(message.sendTime);
      let Y = date.getFullYear()+"-";
      var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
      var D = date.getDate() + ' ';
      var h = date.getHours() + ':';
      var m = date.getMinutes() + ':';
      var s = date.getSeconds();
      let sendTime = Y+M+D+h+m+s;
      let content = encodeURI(message.content);
      let res = await addHistoryMessage(message.id,message.status,message.type,
                sendTime,content,message.toContactId,message.fromUser.id,
                message.fromUser.displayName,message.fromUser.avatar);
      // console.log("储存成功");
    }

    
  },
};
</script>


<style lang="stylus" scoped>
::selection{background:#000;color:#fff;}
body
  font-family "Microsoft YaHei"
  background #f6f6f6 !important
#Content
  width 98.8%
  .scroll-top
    cursor pointer
    position fixed
    bottom 40px
    left 50%
    border-radius 50%
    background #fff
    font-size 18px
    overflow hidden
    width 40px
    height 40px
    line-height 40px
    user-select none
    text-align center
    transform rotate(-45deg) translateX(-50%)
    box-shadow 0 0 30px rgba(0,0,0,0.1);
    &:hover
      font-size 22px
.keyword
  margin: 10px
  width: 80%
a
  color #0c5ed9
  text-decoration none
  font-size 12px
.action
  margin-top 20px
  .lemon-button
    margin-right 10px
    margin-bottom 10px
.link
  font-size 14px
  margin-top 15px
  a
    display inline-block
    margin 0 5px
    text-decoration none
    background #ffba00
    border-radius 4px
    padding 5px 10px
    color rgba(0,0,0,0.8)
.logo
  position relative
  display inline-block
  margin 60px auto
  user-select none
.logo-text
  font-size 38px
.logo-sub
  font-size 18px
  color #999
  font-weight 300
.logo-badge
  position absolute
  top -10px
  left 230px
  background #000
  border-radius 16px
  color #f9f9f9
  font-size 12px
  padding 4px 8px
.title
  font-size 24px
  line-height 26px
  border-left 1px solid #ffba00
  padding-left 15px
  margin-bottom 15px
  margin-top 30px
  user-select none
.table
  width 100%
  border-radius 10px
  background #fff
  border-collapse collapse
  tr
    cursor pointer
  tr:not(.table-head):hover
    background #ffba00 !important
  tr:nth-of-type(even)
    background #f9f9f9
  th
    user-select none
    color #999
  td,
  th
    text-align left
    padding 10px 15px
    font-size 14px
    font-weight normal
.imui-center
  .lemon-wrapper
    border:1px solid #ddd;
  .lemon-drawer
    border:1px solid #ddd;
    border-left:0;
.drawer-content
  padding 15px
.more
  font-size 12px
  line-height 24px
  height 24px
  position absolute
  top 14px
  right 14px
  cursor pointer
  user-select none
  color #f1f1f1
  display inline-block
  border-radius 4px
  background #111
  padding 0 8px
  &:active
    background #999
.bar
  text-align center
  line-height 30px
  background #fff
  margin 15px
  color #666
  user-select none
  font-size 12px
.cover
  text-align center
  user-select none
  position absolute
  top 50%
  left 50%
  transform translate(-50%,-50%)
  i
    font-size 84px
    color #e6e6e6
  p
    font-size 18px
    color #ddd
    line-height 50px
.article-item
  line-height 34px
  cursor pointer
  &:hover
    text-decoration underline
    color #318efd
pre
  background #fff
  border-radius 8px
  padding 15px
.lemon-simple .lemon-container{
  z-index:5
}
.lemon-simple .lemon-drawer{
  z-index:4
}



input#switch[type=checkbox]{
	height: 0;
	width: 0;
	display:none;
}

label#switch-label {
	cursor: pointer;
	text-indent: -9999px;
	width: 34px;
	height: 20px;
	background: #aaa;
	display: block;
	border-radius: 100px;
	position: relative;
}

label#switch-label:after {
	content: '';
	position: absolute;
	top: 2px;
	left: 2px;
	width: 16px;
	height: 16px;
	background: #fff;
	border-radius: 20px;
	transition: 0.3s;
}

input#switch:checked + label {
	background: #0fd547;
}

input#switch:checked + label:after {
	left: calc(100% - 2px);
	transform: translateX(-100%);
}

label#switch-label:active:after {
	width: 20px;
}
</style>